package com.hupu.jrs.ui.pmdetail

import android.app.Activity
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import com.facebook.drawee.view.SimpleDraweeView
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import java.util.regex.Matcher
import java.util.regex.Pattern
import javax.inject.Inject
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.hupu.jrs.R
import com.hupu.jrs.bean.PmDetail
import com.hupu.jrs.ui.browser.BrowserActivity
import com.hupu.jrs.ui.content.ContentActivity
import com.hupu.jrs.ui.thread.list.ThreadListActivity
import com.hupu.jrs.ui.userprofile.UserProfileActivity
import com.hupu.jrs.widget.MyMovementMethod

/**
 * Created by sll on 2016/5/6.
 */
class PmDetailAdapter @Inject
constructor(private val mUserStorage: UserStorage, private val mActivity: Activity) : RecyclerView.Adapter<PmDetailAdapter.ViewHolder>() {

    private var mPmDetails: List<PmDetail> = ArrayList<PmDetail>()

    fun bind(pmDetails: List<PmDetail>) {
        mPmDetails = pmDetails
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        val detail = mPmDetails[position]
        return if (detail.puid.equals(mUserStorage.getUid())) {
            TYPE_USER
        } else {
            TYPE_OTHER
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PmDetailAdapter.ViewHolder {
        return if (viewType == TYPE_USER) {
            ViewHolder(LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_list_pm_user, parent, false))
        } else {
            ViewHolder(LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_list_pm_other, parent, false))
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val detail = mPmDetails[position]
        holder.detail = detail
        val format = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
        val date = Date(java.lang.Long.valueOf(detail.create_time) * 1000)
        holder.tvDate!!.text = format.format(date)
        if (!TextUtils.isEmpty(detail.header)) {
            holder.ivUser!!.setImageURI(Uri.parse(detail.header))
        }
        holder.tvContent!!.movementMethod = MyMovementMethod.getInstance()
        holder.tvContent!!.text = a(detail.content)
    }

    override fun getItemCount(): Int {
        return mPmDetails.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        internal var detail: PmDetail? = null

        @BindView(R.id.tvDate)
        internal var tvDate: TextView? = null
        @BindView(R.id.ivUser)
        internal var ivUser: SimpleDraweeView? = null
        @BindView(R.id.pbReply)
        internal var pbReply: ProgressBar? = null
        @BindView(R.id.tvContent)
        internal var tvContent: TextView? = null

        @OnClick(R.id.ivUser)
        internal fun ivUserClick() {
            UserProfileActivity.startActivity(mActivity, detail!!.puid)
        }

        init {
            ButterKnife.bind(this, itemView)
        }
    }

    private fun a(content: String): SpannableStringBuilder {
        val matcher = Pattern.compile("<a.+?</a>", Pattern.CASE_INSENSITIVE).matcher(content)
        val spannableStringBuilder = SpannableStringBuilder()
        var i = 0
        while (matcher.find()) {
            i = matcher.end()
            val group = matcher.group()
            spannableStringBuilder.append(content.substring(0, i - group.length))
            spannableStringBuilder.append(span(content.substring(i - group.length, i)))
        }
        if (i <= 0) {
            spannableStringBuilder.append(content)
        } else {
            spannableStringBuilder.append(content.substring(i))
        }
        return spannableStringBuilder
    }

    private fun span(text: String): CharSequence {
        val ssb = SpannableStringBuilder(Html.fromHtml(text))
        val spans = ssb.getSpans(0, ssb.length, URLSpan::class.java)
        for (span in spans) {
            val start = ssb.getSpanStart(span)
            val end = ssb.getSpanEnd(span)
            ssb.removeSpan(span)
            ssb.setSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    handlerSpan(span)
                }
            }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        return ssb
    }

    private fun handlerSpan(span: URLSpan) {
        val url = span.url
        if (TextUtils.isEmpty(url)) {
            return
        }
        val uri = Uri.parse(url)
        when (uri.scheme) {
            "kanqiu" -> if (url.contains("topic")) {
                val tid = uri.lastPathSegment
                ContentActivity.startActivity(mActivity, "", tid, "", 1)
            } else if (url.contains("board")) {
                val boardId = uri.lastPathSegment
                ThreadListActivity.startActivity(mActivity, boardId)
            }
            "app" -> {
            }
            "http", "https" -> BrowserActivity.startActivity(mActivity, url)
        }
    }

    companion object {

        private val TYPE_USER = 1
        private val TYPE_OTHER = 2
    }
}
